<template>
  <el-form ref="ruleFormRef" :model="userForm" :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon>
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="userForm.userName" />
    </el-form-item>
    <el-form-item label="密码" prop="userPwd">
      <el-input v-model="userForm.userPwd" />
    </el-form-item>
    <el-form-item label="性别" prop="gender">
      <el-radio-group v-model="userForm.gender" class="ml-4">
        <el-radio label=1 size="large">男</el-radio>
        <el-radio label=0 size="large">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="角色" prop="roleId">
      <el-select v-model="userForm.roleId" class="m-2" placeholder="Select">
        <el-option v-for="item in roleOptions.role" :key="item.id" :label="item.roleName" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import qs from 'qs'

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const userForm = ref({
  userName: '',
  userPwd: '',
  gender: '',
  roleId: 3
})

const rules = reactive<FormRules>({
  userName: [
    {
      required: true,
      message: '用户名不能为空',
      trigger: 'change',
    },
  ],
  userPwd: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'change',
    },
  ],
  gender: [
    {
      required: true,
      message: '性别不能为空',
      trigger: 'change',
    },
  ],
})

const roleOptions = reactive({
  role: [] as any
})

// 异步请求获取下拉框选项
axios.get('http://localhost:8888/role/getRoleList')
  .then(response => {
    roleOptions.role = response.data;
  });

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('http://localhost:8888/user/addUser', qs.stringify(userForm.value))
        .then(response => {
          // 在这里可以处理提交成功后的逻辑
          alert(response.data.msg)
          formEl.resetFields()
        })
        .catch(error => {
          console.log('提交失败', error);
          // 在这里可以处理提交失败后的逻辑
        });
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
  